﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;

using SMSSender.Entities.Models;
using SMSSender.Biz;
using SMSSender.Entities.Utils;

namespace SBK.SMSWindowsService
{
    public partial class SBKSMSService : ServiceBase
    {
        System.Timers.Timer timer;
        EventLog eventLog;
        public SBKSMSService()
        {
            InitializeComponent();

            // Reads settings from app.config
            this.ServiceName = ConfigurationSettings.AppSettings["serviceName"];
            string eventLogName = ConfigurationSettings.AppSettings["eventLogName"];
            string eventLogSource = ConfigurationSettings.AppSettings["eventLogSource"];

            // Initializes eventlog
            if (!EventLog.SourceExists(eventLogSource))
                EventLog.CreateEventSource(eventLogSource, eventLogName);

            eventLog = new EventLog();
            ((System.ComponentModel.ISupportInitialize)(eventLog)).BeginInit();

            eventLog.Source = eventLogSource;

            // Registers the application
            eventLog.Log = eventLogName;

            ((System.ComponentModel.ISupportInitialize)(eventLog)).EndInit();
        }

        protected override void OnStart(string[] args)
        {
            eventLog.WriteEntry("+++++++++++++ START SMS SERVICE +++++++++++++", EventLogEntryType.Warning);

            // Runs the process every X minutes
            int interval = Int32.Parse(ConfigurationSettings.AppSettings["interval"]) * 1000;
            timer = new System.Timers.Timer();
            timer.Interval = interval;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(CollectAndSendSms);
            timer.Start(); 
        }

        protected override void OnStop()
        {
            eventLog.WriteEntry("+++++++++++++ STOP SMS SERVICE +++++++++++++", EventLogEntryType.Warning);
        }

        protected void DataProcess(string RoleKey)
        {
            MessageHistoryInfo messageHistoryInfo = new MessageHistoryInfo();
            SBKSMSGateway.Service1 serviceSoapClient = new SBKSMSGateway.Service1();
            MyConfig myconfig = new MyConfig();
            myconfig.GetMyConfig();

            int n = 0; int result = -1;
            string Conten = "";
            bool Flag = false; bool Status = false;
            List<V_ListPhoneSendSMSInfo> v_ListPhoneSendSMSInfo = new V_ListPhoneSendSMSService().SelectListPhoneSendSMS(RoleKey);
            n = v_ListPhoneSendSMSInfo.Count;
            for (int i = 0; i < n; i++)
            {
                Conten = myconfig.KeyWord;
                switch (v_ListPhoneSendSMSInfo[i].RoleKey.Trim().ToUpper())
                {
                    case "VN":
                        Conten += " VN";
                        break;
                    case "TG":
                        Conten += " TG";
                        break;
                    case "SJC":
                        Conten += " SJC";
                        break;
                    case "BTMC":
                        Conten += " BTMC";
                        break;
                    case "SBJ":
                        Conten += " SBJ";
                        break;
                }
                if (i == n - 1) Flag = true;
                //Send SMS
                result = serviceSoapClient.AutoSMS("84" + v_ListPhoneSendSMSInfo[i].PhoneNumber.Substring(1), myconfig.ServiceNumber,"VN",
                    Conten, "12345678", myconfig.rvUserName, myconfig.rvPassword);
                if (result == 0) Status = true;

                messageHistoryInfo.IdMessage = Guid.NewGuid();
                messageHistoryInfo.PostDate = DateTime.Now;
                messageHistoryInfo.Sender = v_ListPhoneSendSMSInfo[i].PhoneNumber;
                messageHistoryInfo.Reciver = myconfig.ServiceNumber;
                messageHistoryInfo.Conten = Conten;
                messageHistoryInfo.Status = Status;
                messageHistoryInfo.Flag = Flag;
                //Insert in to history
                new MessageHistoryService().Insert(messageHistoryInfo);
            }
        }

        /// <summary>
        /// - Ngay CN: Vang The gio va Vang trong nuoc khong gui SMS
        /// - Ngay T7: Vang The gioi gui 1 tin luc 7h00; Vang trong nuoc gui tin tu 7h30 den 11h30
        /// - Ngay T2 den T6: Vang The gioi gui tin tu 7h00 den 23h00; Vang trong nuoc gui tin tu 7h30 den 17h30
        /// </summary>
        /// <param></param>
        /// <returns></returns>
        protected void CollectAndSendSms(object obj, System.Timers.ElapsedEventArgs e)
        {
            DateTime now = DateTime.Now;
            string strMinute = now.Minute.ToString();
            if (now.Minute < 10) strMinute = "0" + now.Minute.ToString();
            int Time = int.Parse(now.Hour.ToString() + strMinute);

            if ((now.Hour >= 0 && now.Hour < 7)
                || (now.DayOfWeek.ToString().ToUpper() == "SATURDAY" && Time > 1130 && Time <= 2359)
                || now.DayOfWeek.ToString().ToUpper() == "SUNDAY")
                return;

            MessageHistoryService messageHistoryService = new MessageHistoryService();

            //Get date from to SqlServer
            bool? flag = false;
            try { flag = messageHistoryService.SelectTopOne().Flag.Value; }
            catch { flag = false; }

            int _Hour = 0;
            try { _Hour = messageHistoryService.SelectTopOne().PostDate.Value.Hour; }
            catch { _Hour = 0; }
            string _strMinute = "0";
            try { _strMinute = messageHistoryService.SelectTopOne().PostDate.Value.Minute.ToString(); }
            catch { _strMinute = "0"; }
            if (int.Parse(_strMinute) < 10) _strMinute = "0" + _strMinute;
            int _Time = int.Parse(_Hour.ToString() + _strMinute);
            //End Get date from to SqlServer

            string GoldWorl = "TG"; string GoldLocal = "VN','BTMC','SJC','SBJ";

            if (Time >= 700 && Time < 730)
            {
                if (flag == true && _Time >= 700 && _Time < 730)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 730 && Time < 800)
            {
                if (flag == true && _Time >= 730 && _Time < 800)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 800 && Time < 830)
            {
                if ((flag == true && _Time >= 800 && _Time < 830)
                    || (now.DayOfWeek.ToString().ToUpper() == "SATURDAY" && Time >= 800 && Time < 830))
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 830 && Time < 900)
            {
                if (flag == true && _Time >= 830 && _Time < 900)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 900 && Time < 930)
            {
                if ((flag == true && _Time >= 900 && _Time < 930)
                    || (now.DayOfWeek.ToString().ToUpper() == "SATURDAY" && Time >= 900 && Time < 930))
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 930 && Time < 1000)
            {
                if (flag == true && _Time >= 930 && _Time < 1000)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1000 && Time < 1030)
            {
                if ((flag == true && _Time >= 1000 && _Time < 1030)
                    || (now.DayOfWeek.ToString().ToUpper() == "SATURDAY" && Time >= 1000 && Time < 1030))
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1030 && Time < 1100)
            {
                if (flag == true && _Time >= 1030 && _Time < 1100)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1100 && Time < 1130)
            {
                if ((flag == true && _Time >= 1100 && _Time < 1130)
                    || (now.DayOfWeek.ToString().ToUpper() == "SATURDAY" && Time >= 1100 && Time < 1130))
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1130 && Time < 1200)
            {
                if (flag == true && _Time >= 1130 && _Time < 1200)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1200 && Time < 1230)
            {
                if (flag == true && _Time >= 1200 && _Time < 1230)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1230 && Time < 1300)
            {
                if (flag == true && _Time >= 1230 && _Time < 1300)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1300 && Time < 1330)
            {
                if (flag == true && _Time >= 1300 && _Time < 1330)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1330 && Time < 1400)
            {
                if (flag == true && _Time >= 1330 && _Time < 1400)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1400 && Time < 1430)
            {
                if (flag == true && _Time >= 1400 && _Time < 1430)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1430 && Time < 1500)
            {
                if (flag == true && _Time >= 1430 && _Time < 1500)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1500 && Time < 1530)
            {
                if (flag == true && _Time >= 1500 && _Time < 1530)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1530 && Time < 1600)
            {
                if (flag == true && _Time >= 1530 && _Time < 1600)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1600 && Time < 1630)
            {
                if (flag == true && _Time >= 1600 && _Time < 1630)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1630 && Time < 1700)
            {
                if (flag == true && _Time >= 1630 && _Time < 1700)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1700 && Time < 1730)
            {
                if (flag == true && _Time >= 1700 && _Time < 1730)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1730 && Time < 1800)
            {
                if (flag == true && _Time >= 1730 && _Time < 1800)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1800 && Time < 1830)
            {
                if (flag == true && _Time >= 1800 && _Time < 1830)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1830 && Time < 1900)
            {
                //Do not send SMS
                return;

                if (flag == true && _Time >= 1830 && _Time < 1900)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 1900 && Time < 1930)
            {
                if (flag == true && _Time >= 1900 && _Time < 1930)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 1930 && Time < 2000)
            {
                //Do not send SMS
                return;

                if (flag == true && _Time >= 1930 && _Time < 2000)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 2000 && Time < 2030)
            {
                if (flag == true && _Time >= 2000 && _Time < 2030)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 2030 && Time < 2100)
            {
                //Do not send SMS
                return;

                if (flag == true && _Time >= 2030 && _Time < 2100)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 2100 && Time < 2130)
            {
                if (flag == true && _Time >= 2100 && _Time < 2130)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 2130 && Time < 2200)
            {
                //Do not send SMS
                return;

                if (flag == true && _Time >= 2130 && _Time < 2200)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 2200 && Time < 2230)
            {
                if (flag == true && _Time >= 2200 && _Time < 2230)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }
            if (Time >= 2230 && Time < 2300)
            {
                //Do not send SMS
                return;

                if (flag == true && _Time >= 2230 && _Time < 2300)
                    return;
                this.DataProcess(GoldLocal);
                return;
            }

            if (Time >= 2300 && Time < 2330)
            {
                if (flag == true && _Time >= 2300 && _Time < 2330)
                    return;
                this.DataProcess(GoldWorl);
                return;
            }

        }

    }
}
